/*
 * Copyright Groupe Adeo 2009
 * 
 * Licensed under New BSD License : http://www.opensource.org/licenses/bsd-license.php
 */
package com.adeoservices.gwt.dispatch.spring.client;

import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.dispatch.shared.Action;
import net.customware.gwt.dispatch.shared.Result;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

/**
 * 
 * @author Olivier HEDIN / Adeo Services
 *
 */
public class SpringDispatchServiceAsyncImpl implements DispatchAsync {

	private static final SpringDispatchServiceAsync realService;

	static {
		realService = GWT.create(SpringDispatchService.class);
		final String endpointURL = getModuleBaseURL() + "dispatch.rpc";

		((ServiceDefTarget) realService).setServiceEntryPoint(endpointURL);
	}

	public static String getModuleBaseURL() {
		return GWT.getHostPageBaseURL();
	}

	public SpringDispatchServiceAsyncImpl() {
	}

    public <A extends Action<R>, R extends Result> void execute( final A action, final AsyncCallback<R> callback ) {
        realService.execute( action, new AsyncCallback<Result>() {
            public void onFailure( Throwable caught ) {
                callback.onFailure( caught );
            }

            @SuppressWarnings("unchecked")
			public void onSuccess( Result result ) {
                callback.onSuccess( ( R ) result );
            }
        } );
    }

}